package imy.virtual.a64support;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.imy.virtual.client.core.VirtualCore;
import com.imy.virtual.client.ipc.VActivityManager;
import com.imy.virtual.client.stub.VASettings;
import com.imy.virtual.helper.utils.LaunchIntentUtils;
import com.imy.virtual.remote.InstallResult;
import com.virtual.common.utils.ToastUtil;

import imy.virtual.a64support.util.CommonUtils;
import imy.virtual.a64support.util.PermissionHelper;

public class PermissionActivity extends AppCompatActivity {
  private static final int REQUEST_EXTERNAL_STORAGE = 1;
  private static final String TAG ="PermissionActivity" ;
  private static String[] PERMISSIONS_STORAGE = {
      "android.permission.READ_EXTERNAL_STORAGE",
      "android.permission.WRITE_EXTERNAL_STORAGE" };

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    //if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.O
    //    || android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
    //  setTheme(R.style.App_8);
    //} else {
    //  setTheme(R.style.App);
    //}
    super.onCreate(savedInstanceState);
    //Window window = getWindow();
    //window.setGravity(Gravity.LEFT | Gravity.TOP);
    //WindowManager.LayoutParams params = window.getAttributes();
    //params.x = 0;
    //params.y = 0;
    //params.height = 1;
    //params.width = 1;
    //window.setAttributes(params);
    setContentView(R.layout.activity_permission);
    TextView textView = findViewById(R.id.text_64);
    //检测权限
    //检测通知栏
    boolean notificationEnabled = PermissionHelper.isNotificationEnabled(PermissionActivity.this);
    if (!notificationEnabled){
      CommonUtils.openNotificationSetting(this);
    }
    int permission = ActivityCompat.checkSelfPermission(this,
        "android.permission.WRITE_EXTERNAL_STORAGE");
    if (permission != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
    }else {
      //有权限
      installOrStart(getIntent());
    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    installOrStart(intent);
  }

  private void installOrStart(final Intent intent) {
    //检测是否启动了X进程
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (!VirtualCore.get().isEngineLaunched()){
          VirtualCore.get().waitForEngine();
        }
        realStart(intent);
      }
    }).start();
  }

  private void realStart(Intent intent) {
    final String path =intent.getStringExtra(VASettings.APK_PATH);
    final String packageName = intent.getStringExtra(VASettings.APK_PACKAGE);
    if (path==null || packageName==null){
      return;
    }
    Log.i(TAG,"path:"+path + " package:"+packageName);
    boolean appInstalled = VirtualCore.get().isAppInstalled(packageName);
    if (!appInstalled){

      //showToast("开始安装");
      new Thread(new Runnable() {
        @Override
        public void run() {
          InstallResult installResult = VirtualCore.get().installPackage(path, 0);
          if (installResult.isSuccess){
            Intent launchIntent = LaunchIntentUtils.getLaunchIntent(packageName, 0);
            VActivityManager.get().startActivity(launchIntent,0);
            finish();
          }else {
            showToast("64启动失败:"+installResult.error);
          }
        }
      }).start();
    }else {
      Intent launchIntent = LaunchIntentUtils.getLaunchIntent(packageName, 0);
      VActivityManager.get().startActivity(launchIntent,0);
      finish();
    }
  }

  private void showToast(final String s) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(PermissionActivity.this,s,Toast.LENGTH_LONG).show();

      }
    });
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_EXTERNAL_STORAGE) {
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG,"权限通过");
      } else {
        Log.i(TAG,"权限拒绝");
        finish();
      }
    }
  }
}
